package com.dz.scrm.mvp.presenter

import android.Manifest
import android.Manifest.permission.REQUEST_INSTALL_PACKAGES
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.core.content.FileProvider
import com.dz.scrm.app.config.*
import com.dz.scrm.constant.INTENT_APK_PATHL
import com.dz.scrm.constant.INTENT_REQUEST_INSTALL
import com.dz.scrm.constant.INTENT_URL
import com.dz.scrm.mvp.model.api.APP_UPLOAD_FILE_URL
import com.dz.scrm.mvp.model.entity.*
import com.dz.scrm.mvp.model.repository.UserRepository
import com.dz.scrm.utils.*
import com.google.gson.Gson
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import me.jessyan.art.di.component.AppComponent
import me.jessyan.art.mvp.BasePresenter
import me.jessyan.art.mvp.Message
import me.jessyan.art.utils.PermissionUtil
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import okhttp3.*
import org.litepal.LitePal
import org.litepal.extension.find
import java.io.File
import java.io.IOException
import kotlin.jvm.Throws

/**
 * 作者：fanda
 * 日期：2021/4/23 10:59
 * 描述：
 */
class DZPresent(private val appComponent: AppComponent, val rxPermissions: RxPermissions) :
        BasePresenter<UserRepository>(appComponent.repositoryManager().createRepository(UserRepository::class.java)) {

    private val mOkHttpClient = OkHttpClient()
    private val mErrorHandler = appComponent.rxErrorHandler()

    // 未上传录音文件的数据列表
    private var cachePhoneRecordList = mutableListOf<CachePhoneRecord>()

    fun requestPermission(msg: Message) {
        PermissionUtil.requestPermission(object : PermissionUtil.RequestPermission {
            override fun onRequestPermissionFailureWithAskNeverAgain(permissions: MutableList<String>?) {
                msg.what = WHAT_REQUEST_PERMISSION_ALWAYS_DISAGREE
                msg.handleMessageToTargetUnrecycle()
            }

            override fun onRequestPermissionSuccess() {
                msg.what = WHAT_REQUEST_PERMISSION_AGREE
                msg.handleMessageToTargetUnrecycle()
            }

            override fun onRequestPermissionFailure(permissions: MutableList<String>?) {
                msg.what = WHAT_REQUEST_PERMISSION_DISAGREE
                msg.handleMessageToTargetUnrecycle()
            }

        }, rxPermissions, mErrorHandler, Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_CALL_LOG, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }

    /***
     * 检测更新
     */
    fun checkVersion(msg: Message) {
        mModel.checkVersion().doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).doFinally {
            msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
        }.subscribe(object : ErrorHandleSubscriber<BaseResponse<CheckVersionBean?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<CheckVersionBean?>) {
                msg.what = WHAT_CHECK_VERSION
                msg.obj = response.data
                LoggerUtils.d(response.toString())
            }
        })
    }

    /***
     * 上传通话记录
     */
    fun postPhoneRecord(msg: Message) {
        val params = msg.obj as PhoneRecordParams
        mModel.postPhoneRecord(params).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).subscribe(object : ErrorHandleSubscriber<BaseResponse<DZResponse?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<DZResponse?>) {
                if (response.isSuccess()) {
                    msg.what = WHAT_POST_PHONE_RECORD_SUCCESS
                    msg.obj = response.data
                    msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
                } else {
                    msg.target.showMessage(response.msg ?: "")
                }
                LoggerUtils.d(response.toString())
            }
        })
    }

    /***
     * 获取拨打电话的名字
     */
    fun GetUerPhoneName(msg: Message, phone: String) {
        msg.target.showLoading()
        mModel.GetUerPhoneName(phone).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).doFinally {
            msg.target.hideLoading()
            msg.handleMessageToTarget() //方法最后必须调HandleMessageToTarget,将消息所有引用清空后回收进消息池
        }.subscribe(object : ErrorHandleSubscriber<BaseResponse<LoginCompanyBean?>>(mErrorHandler) {
            override fun onNext(response: BaseResponse<LoginCompanyBean?>) {
                msg.what = WHAT_PHONE_NAME
                msg.obj = response.data
                LoggerUtils.d(response.toString())
            }
        })
    }

    fun queryNoUploadFileDatas(msg: Message) {
        Observable.just(0).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).subscribe(object : ErrorHandleSubscriber<Int>(mErrorHandler) {
            override fun onNext(response: Int) {
                cachePhoneRecordList = LitePal.where("user_id = ? and tenant_id = ? and fileUrl != ?", getUserId(), getTenantId(), "").find<CachePhoneRecord>().toMutableList()
                LoggerUtils.d("未上传文件数量：${cachePhoneRecordList.size} ，$cachePhoneRecordList")
                if (cachePhoneRecordList.isNotEmpty()) {
                    cachePhoneRecordList.first().apply {
                        upload(msg, fileUrl, uid )
                    }
                } else {
                    msg.recycle()
                }
            }
        })
    }

    fun upload(msg: Message, fileUrl: String, uid: String) {
        Observable.just(0).doOnSubscribe { d: Disposable ->
            addDispose(d)
        }.compose(io_main_retry()).subscribe(object : ErrorHandleSubscriber<Int>(mErrorHandler) {
            override fun onNext(response: Int) {
                val requestBody: RequestBody = MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", File(fileUrl).name,
                                RequestBody.create(MediaType.parse("multipart/form-data"), File(fileUrl)))
                        .addFormDataPart("uid", uid) // 提交内容字段
                        .build()
                val request: Request = Request.Builder() //                .header("Authorization", "ClientID" + UUID.randomUUID())
                        .header("Dz-Auth", "bearer ${getToken()}")
                        .url(APP_UPLOAD_FILE_URL)
                        .post(requestBody)
                        .build()
                Log.e("HH", "request --》 " + Gson().toJson(request))
                val call: Call = mOkHttpClient.newCall(request)
                call.enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Log.e("HH", "failure upload!" + e.message)
                    }

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: Response) {
                        if (response.isSuccessful) {
                            if (msg.obj as Boolean) {
                                msg.what = WHAT_UPLOAD_FILE_SUCCESS
                                msg.handleMessageToTarget()
                            } else {
                                // 上传音频文件未上传成功的历史数据
                                if (cachePhoneRecordList.isNotEmpty()) {
                                    // 把音频链接设为空
                                    cachePhoneRecordList.first().fileUrl = ""
                                    // 更新一下数据库
                                    cachePhoneRecordList.first().save()
                                    // 移除第一条数据
                                    cachePhoneRecordList.removeAt(0)
                                    // 判断移除后的列表是否为空
                                    if (cachePhoneRecordList.isNotEmpty()) {
                                        // 找到第一条数据，继续进行上传
                                        cachePhoneRecordList.first().apply {
                                            upload(msg, fileUrl, uid )
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
            }
        })
    }
}